<template>
    <el-card shadow="never">
		<el-form
            :inline="true"
            :model="queryForm"
            @keyup.enter="onSearch()">
			<el-form-item>
				<el-input
                    v-model="queryForm.username"
                    placeholder="用户名"
                    clearable>
                </el-input>
			</el-form-item>
			<el-form-item>
				<el-input
                    v-model="queryForm.mobile"
                    placeholder="手机号"
                    clearable>
                </el-input>
			</el-form-item>
			<el-form-item>
				<el-select
                    v-model="queryForm.gender"
                    placeholder="性别"
                    style="width: 80px;"
                    clearable>
                    <el-option label="男" value="0" />
                    <el-option label="女" value="1" />
                </el-select>
			</el-form-item>
			<el-form-item>
				<el-button @click="onSearch()">查询</el-button>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="handleUser()">新增</el-button>
			</el-form-item>
			<el-form-item>
				<el-button type="danger" @click="deleteBatch()">删除</el-button>
			</el-form-item>
		</el-form>
        
		<el-table
            v-loading="loading"
            :data="userList"
            style="width: 100%"
            border
            @selection-change="selectUserId">
			<el-table-column
                type="selection"
                header-align="center"
                align="center"
                width="50">
            </el-table-column>
			<el-table-column
                prop="username"
                label="用户名"
                header-align="center"
                align="center">
            </el-table-column>
			<el-table-column
                prop="realName"
                label="姓名"
                header-align="center"
                align="center">
            </el-table-column>
			<el-table-column
                prop="gender"
                label="性别"
                header-align="center"
                align="center">
                <template #default="scope">
                    {{ scope.row.gender === 0 ? '男' : (scope.row.gender === 1 ? '女' : '未知') }}
                </template>
            </el-table-column>
			<el-table-column
                prop="mobile"
                label="手机号"
                show-overflow-tooltip
                header-align="center"
                align="center">
            </el-table-column>
			<el-table-column
                prop="email"
                label="邮箱"
                show-overflow-tooltip
                header-align="center"
                align="center">
            </el-table-column>
			<el-table-column
                prop="orgData.name"
                label="所属机构"
                show-overflow-tooltip
                header-align="center"
                width="100"
                align="center">
            </el-table-column>
			<el-table-column
                prop="status"
                label="状态"
                header-align="center"
                align="center">
                <template #default="scope">
                    {{ scope.row.status === 0? '禁用' : '正常' }}
                </template>
            </el-table-column>
			<el-table-column
                prop="createTime"
                label="创建时间"
                show-overflow-tooltip
                header-align="center"
                align="center"
                width="170">
                <template #default="scope">
                    {{ scope.row.createTime.replace('T', ' ').split('+')[0] }}
                </template>
            </el-table-column>
			<el-table-column
                label="操作" fixed="right"
                header-align="center" align="center"
                width="150">
				<template #default="scope">
					<el-button type="primary" link @click="handleUser(scope.row.id)">修改</el-button>
					<el-button type="primary" link @click="deleteBatch(scope.row.id)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
        
        <div style="margin-top: 20px">
            <el-pagination
                layout="prev, pager, next"
                v-model:current-page="pagination.page"
                :page-size="pagination.limit"
                :total="pagination.total"
                @current-change="onPageChange"
                background
            >
            </el-pagination>
        </div>

        <!-- 用户弹窗组件，新增/编辑 -->
        <UserDlg ref="userDlgRef" @refresh="getUserList" />
    </el-card>
</template>

<script setup>
import { reactive, ref, onMounted, computed } from 'vue'
import { userStore } from '@/store/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import UserDlg from './user_dlg.vue'

const useUserStore = userStore()
// 直接从store获取数据
const userList = computed(
    () => useUserStore.userList
)
const pagination = computed(
    () => useUserStore.pagination
)
const queryForm = reactive({
    username: '',
    mobile: '',
    gender: ''
})

onMounted(() => {
    getUserList()
})

const loading = ref(false)
// 获取用户列表
const getUserList = async () => {
  try {
    loading.value = true
    await useUserStore.getUserList(queryForm)
  } catch (error) {
    console.error('获取用户列表失败:', error)
  } finally {
    loading.value = false
  }
}

const onPageChange = (page) => {
    useUserStore.pagination.page = page
    getUserList()
}

const onSearch = () => {
    // 重置到第一页
    useUserStore.pagination.page = 1
    // 重新获取用户列表 自动使用当前的 queryForm 和 pagination 参数
    getUserList()
}

const userDlgRef = ref(null) // 新增/修改组件的引用
const handleUser = (id) => {
    if (id) {
        userDlgRef.value.init(id) // 修改模式
    } else {
        userDlgRef.value.init() // 新增模式
    }
}

const selectedIds = ref([]) // 存储选中ID
const selectUserId = (selection) => {
    selectedIds.value = selection.map(item => item.id)
    // console.log('选中的用户ID：', selectedIds.value)
}

const deleteBatch = async(key) => {
    const ids = key ? [key] : selectedIds.value
    if (ids.length === 0) {
      ElMessage.warning('请选择删除记录')
      return
    }

    try {
        const confirm = await ElMessageBox.confirm('确定进行删除操作?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        
        if (confirm === 'confirm') {
            console.log('删除用户ID:', ids)
            // await useUserStore.deleteBatch(ids)
            ElMessage.success('删除成功')
            await getUserList() // 刷新列表
        }
    } catch (error) {
        // 用户点击取消或关闭弹窗
        console.log('删除操作已取消')
    }
}
</script>

<style lang="scss" scoped>
:deep(.el-form-item) {
    margin-right: 20px;
}
</style>